package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.entity.Result;
import com.itheima.pojo.OrderSetting;
import com.itheima.service.OrderSettingSerivce;
import com.itheima.util.POIUtils;

import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 预约设置
 */
@RestController
@RequestMapping("/ordersetting")
public class OrderSettingController {

    @Reference
    private OrderSettingSerivce orderSettingSerivce;

    /**
     * Excel文件上传，解析文件内容保存到数据库
     *
     * @param excelFile
     * @return
     */
    @RequestMapping("/upload")
    public Result upload(MultipartFile excelFile) {
        try {
            //利用工具类读取excel表格中的内容
            List<String[]> excel = POIUtils.readExcel(excelFile);
            if (excel != null && excel.size() > 0) {
                List<OrderSetting> orderSettings = new ArrayList<>();
                for (String[] strings : excel) {//遍历list集合
                    String orderDate=strings[0];//第一列数据即为预约设置日期
                    String number=strings[1];//第二列数据为可预约人数
                    OrderSetting orderSetting = new OrderSetting(new Date(orderDate),Integer.parseInt(number));//将获得的这两项数据封装到预约设置pojo实体类中
                    orderSettings.add(orderSetting);
                }
                //将由每一个预约设置封装成的list集合传给service层
                orderSettingSerivce.add(orderSettings);
            }
        } catch (IOException e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.IMPORT_ORDERSETTING_FAIL);
        }
        return new Result(true,MessageConstant.IMPORT_ORDERSETTING_SUCCESS);
    }

    //根据日期来查询指定月份的预约设置信息
    @RequestMapping("/getOrderSettingByMonth")
    public Result getOrderSettingByMonth(String date){//date格式：2020-01
        try {
            List<Map> list=orderSettingSerivce.getOrderSettingByMonth(date);
            return new Result(true,MessageConstant.GET_ORDERSETTING_SUCCESS,list);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.GET_ORDERSETTING_FAIL);
        }
    }

    @RequestMapping("/editNumberByDate")
    public Result editNumberByDate(@RequestBody OrderSetting orderSetting){
        try {
            orderSettingSerivce.editNumberByDate(orderSetting);
            return new Result(true,MessageConstant.ORDERSETTING_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.ORDERSETTING_FAIL);
        }
    }
}
